<?php
/**
 * Created by PhpStorm.
 * User: jz
 * Date: 16/7/7
 * Time: 下午1:57
 */
function get_user_urls($username)
{
    $conn = db_connect();
    $res = $conn->query(sprintf('select bm_URL from bookmark where username = \'%s\'', $username));
    if (!$res){
        return false;
    }
    while (($row = $res->fetch_row()) == true){
        $urls[] = $row[0];
    }
    return $urls;
}

function is_url($s)  {
    return preg_match('/^http[s]?:\/\/'.
        '(([0-9]{1,3}\.){3}[0-9]{1,3}'. // IP形式的URL- 199.194.52.184  
        '|'. // 允许IP和DOMAIN（域名）  
        '([0-9a-z_!~*\'()-]+\.)*'. // 域名- www.  
        '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.'. // 二级域名  
        '[a-z]{2,6})'.  // first level domain- .com or .museum  
        '(:[0-9]{1,4})?'.  // 端口- :80  
        '((\/\?)|'.  // a slash isn't required if there is no file name  
        '(\/[0-9a-zA-Z_!~\'\(\)\[\]\.;\?:@&=\+\$,%#-\/^\*\|]*)?)$/',
        $s) == 1;
}  

function add_bm($url)
{
    $user = $_SESSION['valid_user'];
    $conn = db_connect();
    $query = sprintf('insert into bookmark values(\'%s\', \'%s\')', $user, $url);
//    echo $query . '<br>';
    $res = $conn->query($query);
    if (!$res){
        throw new Exception('添加标签失败');
    }
    return true;

    
}
function del_bm($user, $url)
{
    $conn = db_connect();
    $query = sprintf('delete from bookmark where username = \'%s\' and bm_URL = \'%s\'', $user, $url);
    $res = $conn->query($query);
    if (!$res){
        return false;
    }
    return true;
}

function get_recommend_urls($user, $popularity = 1)
{
    
    $query = sprintf(
      '
        select bm_URL from bookmark where username in 
          (select distinct(b2.username)
          from bookmark as b1, bookmark as b2
          where b1.bm_URL = b2.bm_URL 
          and b1.username != b2.username
          and b1.username = \'%s\')
          and bm_URL not in (
            select bm_URL from bookmark where username = \'%s\'
          )
          group by bm_URL
          having count(bm_URL) > %s
      ', $user, $user, $popularity  
    );
    echo $query . "<br>";
    $conn = db_connect();
    
    $res = $conn->query($query);
    if (!$res){
        throw new Exception('无法获取推荐标签');
    }
    if ($res->num_rows == 0){
        throw new Exception('当前没有推荐标签');
    }
    $urls = array();
    while (1){
        $row = $res->fetch_object();
        if ($row){
            $urls[] = $row->bm_URL;
        }else {
            return $urls;
        }
    }
}








